<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Order;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit)->each(function($item,$key){
                        switch($item['status'])
                        {
                            case 1;
                                $item['status'] = '待支付';
                                break;
                            case 2;
                                $item['status'] = '待发货';
                                break;
                            case 3;
                                $item['status'] = '待收货';
                                break;
                            case 4;
                                $item['status'] = '退款中';
                                break;
                            case 5;
                                $item['status'] = '已完成';
                                break;
                            case 6;
                                $item['status'] = '已退款';
                                break;
                            case 7;
                                $item['status'] = '已取消';
                                break;
                        }
                        switch($item['type'])
                        {
                            case 2;
                                $item['type'] = '微信';
                                break;
                            case 1;
                                $item['type'] = '余额';
                                break;
                            case 3;
                                $item['type'] = '爱心值';
                                break;
                        }
                        $address = Db::name('user_address')->where('id',$item['address_id'])->find();

                        $item['uaname'] = $address['name'];
                        $item['address'] = $address['provincial'].$address['city'].$address['area'].$address['address'];
                        $item['phone'] = $address['phone'];
                        return $item;
                });

            
            $money = Db::name('order')->where($where)->sum('money');

            $result = array("total" => $list->total(), "rows" => $list->items(),"extend" => ['money' => $money]);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $status = Db::name('goods')->where('id',$ids)->value('status');
//            if($status != 1)$this->error(__('该订单已发货或者待支付状态'));

            $goods = Db::name('order')->where('id',$ids)->update(['oddnumbers'=>$params['oddnumbers'],'express'=>$params['express'],'ex_time'=>time(),'status'=>3]);
            if($goods)
            {
                $this->success(__('添加成功'));
            }else{
                $this->error(__('添加失败'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /*
     * 详情
     * */
    public function desc($ids = null)
    {
        $row = $this->model->get($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        if ($this->request->isPost()) {

            $params = $this->request->param();
            if(Db::name('order')->where('id',$ids)->value('status') != 4)$this->error(__('该状态不是退款,请勿操作'));

            Db::startTrans();
            try{
                $data = Db::name('order')->where(['status'=>4,'id'=>$ids])->find();

                if($data['type'] == 3 || $data['type'] == 1)
                {
                    // 退款记录;
                    Db::name('order')->where('id',$ids)->update(['status'=>6]);
                    if($data['type'] == 3)
                    {
                        // 返还积分
                        Db::name('user')->where('id',$data['user_id'])->setInc('score',$data['money']);
                    }else{
                        // 返还余额
                        Db::name('user')->where('id',$data['user_id'])->setInc('money',$data['money']);
                    }
                }else{
                    if($data['pid'] == 0)
                    {
                        $price = $data['money'];
                    }else{
                        $price = Db::name('order')->where(['id'=>$data['pid']])->value('money');
                    }
                    
                    // $data['pid'] == 0 ? $price = $data['money'] : $price = "";
                    
                    $config = Config('wechat_pay');
                    $param = [];
                    $metas = range(0, 9);
                    $metas = array_merge($metas, range('A', 'Z'));
                    $metas = array_merge($metas, range('a', 'z'));
                    $noncestr = '';
                    for ($i = 0; $i < 16; $i++) {
                        $noncestr .= $metas[rand(0, count($metas) - 1)];//生成签名的随机串
                    }
                    $param['appid']         = $config['app_id'];
                    $param['mch_id']        = $config['mch_id'];
                    $param['nonce_str']     = $noncestr;
                    $param['out_refund_no'] = $data['order_id'];
                    $param['transaction_id']= $data['transaction_id'];
                    $param['total_fee']     = intval($price * 100);
                    $param['refund_fee']    = intval($price * 100);
                    // $param['total_fee'] = 1;
                    // $param['refund_fee'] = 1;
                    $param['sign'] = $this->getSign($param, $config['key']);
                    $xmldata = $this->arrayToXm($param);
                    $xmlresult = $this->postXmlSSLCurl($xmldata, 'https://api.mch.weixin.qq.com/secapi/pay/refund',30);

                    $result = $this->xmlToArray($xmlresult);

                    if($result['return_code'] == "SUCCESS" && $result['result_code'] == "SUCCESS")
                    {
//                        $refund = [
//                            'orderno' => $data['order_id'],
//                            'money'   => $data['money'] * 100,
//                            'pay_time'=> time(),
//                            'status'  => 2,// 成功
//                            'update_time'=> time()
//                        ];
                        // 退款记录;
                        Db::name('order')->where('id',$ids)->update(['status'=>6]);
                        if($data['pid'] != 0)
                        {
                            Db::name('order')->where('transaction_id',$data['transaction_id'])->update(['status'=>6]);
                        }
                    }elseif($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'FAIL'){
                        $this->success(__($result['err_code_des']));
                    }else{
                        $this->success(__($result['return_msg']));
                    }
                }


                Db::commit();
                $this->success(__('退款成功'));
            }catch(Exception $exception){
                Db::rollback();
                $this->success(__('退款失败'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }



    /*
    * 对要发送到微信统一下单接口的数据进行签名
    */
    protected function getSign($Obj, $key)
    {

        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);

        $String = $this->formatBizQueryParaMap($Parameters, false);

        //签名步骤二：在string后加入KEY
        $String = $String . "&key=" . $key;
        //签名步骤三：MD5加密
        $String = md5($String);
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);

        return $result_;
    }

    /*
     *排序并格式化参数方法，签名时需要使用
     */
    protected function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar = "";
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }

    /*
    * 生成随机字符串方法
    */
    protected function createNoncestr($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    //数组转字符串方法
    protected function arrayToXm($arr)
    {

        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }

    protected static function xmlToArray($xml)
    {
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }

    //需要使用证书的请求
    private function postXmlSSLCurl($xml, $url, $second = 30)
    {

        $ch = curl_init();
        //超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //设置证书
        //使用证书：cert 与 key 分别属于两个.pem文件
        //默认格式为PEM，可以注释
//        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
//        curl_setopt($ch, CURLOPT_SSLCERT, getcwd().'/apiclient_cert.pem');
//        //默认格式为PEM，可以注释
//        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
//        curl_setopt($ch, CURLOPT_SSLKEY, getcwd().'/apiclient_key.pem');

        curl_setopt($ch, CURLOPT_SSLCERT,getcwd().'/apiclient_cert.pem');
        curl_setopt($ch, CURLOPT_SSLKEY,getcwd().'/apiclient_key.pem');
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        $data = curl_exec($ch);

        //返回结果
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            echo "curl出错，错误码:$error" . "<br>";
            curl_close($ch);
            return false;
        }
    }


}
